import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';

const lineNumberFlag = 'line-number';
final quotes = File('quotes.txt');
const stronger = 'That which does not kill us makes us stronger. -Nietzsche';

Future<void> main(List<String> arguments) async {
  exitCode = 0;
  final parser =
      ArgParser()..addFlag(lineNumberFlag, negatable: false, abbr: 'n');
  final argResults = parser.parse(arguments);

  // 明确分离两种模式
  if (argResults.rest.isNotEmpty) {
    // 文件模式
    await dcat(
      argResults.rest,
      showLineNumbers: argResults[lineNumberFlag] as bool,
    );
  } else {
    // 交互模式
    stdout.writeln('Enter text (Ctrl+Z then Enter to end):');
    await stdin.pipe(stdout);
  }

  // 文件操作
  await _handleQuotes();

  // 环境变量打印
  final envVarMap = Platform.environment;
  print('\nEnvironment variables:');
  print('PWD = ${envVarMap['PWD']}');
  print('PATH = ${envVarMap['PATH']}');
}

Future<void> _handleQuotes() async {
  await quotes.writeAsString('$stronger\n', mode: FileMode.append);
  final writer = quotes.openWrite(mode: FileMode.append);
  writer.writeln(
    "Don't cry because it's over, smile because it happened. -Dr. Seuss",
  );
  await writer.close();
}

Future<void> dcat(List<String> paths, {bool showLineNumbers = false}) async {
  for (final path in paths) {
    var lineNumber = 1;
    final lines = utf8.decoder
        .bind(File(path).openRead())
        .transform(const LineSplitter());
    try {
      await for (final line in lines) {
        if (showLineNumbers) {
          stdout.write('${lineNumber++} ');
        }
        stdout.writeln(line);
      }
    } catch (_) {
      await _handleError(path);
    }
  }
}

Future<void> _handleError(String path) async {
  if (await FileSystemEntity.isDirectory(path)) {
    stderr.writeln('error: $path is a directory');
  } else {
    exitCode = 2;
  }
}
